import { createRouter, createWebHistory } from 'vue-router'
import store from "../store"

const routes = [
  {
    path: '/',
    redirect: "/home"
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('../views/LoginView.vue')
  },
  {
    path: '/home',
    name: 'home',
    component: () => import('../views/HomeView.vue'),
    redirect: '/goods',   
    children: [
      {
        path: '/goods/add',
        component: () => import('../views/AddGoodsView.vue')
      }
    ]
  },
  {
    // 配置所有未定义,不存在的路由路径
    path: '/:catchAll(.*)',
    component: () => import('../views/404.vue')
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

// 动态路由规则
const routePaths = {
  'users': () => import('../views/UsersView.vue'),
  'rights': () => import('../views/RightsView.vue'),
  'roles': () => import('../views/RolesView.vue'),
  'categories': () => import('../views/CategoryView.vue'),
  'params': () => import('../views/ParamsView.vue'),
  'goods': () => import('../views/GoodsView.vue'),
  'orders': () => import('../views/OrderView.vue'),
  'reports': () => import('../views/ReportView.vue')
}

// 定义初始化动态路由的函数
router.init = ()=>{
  // 如果状态管理中有menus, 动态创建路由
  if(store.state.menus.length > 0){
    store.state.menus.forEach(item1 => {
      item1.children.forEach(item2 => {
        // 动态添加子路由, 第一个参数为父级路由定义的name字段(不写第一个参数为添加根路由)
        router.addRoute("home", {
          path: "/" + item2.path,
          component: routePaths[item2.path]
        })
      })
    })
  }
}
// 初始化动态路由(刷新页面时调用)
router.init()

// 全局路由守卫,判断是否登录,如果没登陆就跳到登录页
router.beforeEach((to,from,next)=>{
  if(to.path === "/login") next(); // 登录页直接放行
  else if(store.state.token) next();  // 已登录,放行
  else next("/login") // 未登录,强制跳转登录页
})

export default router
